package controller;

/*
 * Action for viewing list of surveys that researcher has created.
 * At the moment, we use sid for display, but in the future, have them input the title for each survey they create.
 */

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import formbeans.BasicAnswerForm;
import formbeans.BinaryQuestionForm;
import formbeans.LikertQuestionForm;
import formbeans.MultipleChoiceQuestionForm;
import formbeans.MultipleSelectionQuestionForm;
import formbeans.NetworkBinaryQuestionForm;
import helper.QuestionType;
import helper.UserType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import databeans.Answer;
import databeans.Entity;
import databeans.EntityClass;
import databeans.MultipleChoiceq;
import databeans.Numericq;
import databeans.Question;
import databeans.Survey;
import databeans.User;

import model.AnswerDAO;
import model.BinaryqDAO;
import model.ContinuousqDAO;
import model.EntityClassDAO;
import model.MultipleChoiceqDAO;
import model.LikertqDAO;
import model.EntityDAO;
import model.Model;
import model.NumericqDAO;
import model.QuestionDAO;
import model.SurveyDAO;
import model.UserDAO;

public class ViewSurveyAction extends Action {
	private FormBeanFactory<BasicAnswerForm> basicFormFactory = FormBeanFactory.getInstance(BasicAnswerForm.class);
	private FormBeanFactory<BinaryQuestionForm> binqFormFactory = FormBeanFactory.getInstance(BinaryQuestionForm.class);
	private FormBeanFactory<LikertQuestionForm> likertFormFactory = FormBeanFactory.getInstance(LikertQuestionForm.class);
	private FormBeanFactory<MultipleChoiceQuestionForm> mcFormFactory = FormBeanFactory.getInstance(MultipleChoiceQuestionForm.class);
	private FormBeanFactory<MultipleSelectionQuestionForm> msFormFactory = FormBeanFactory.getInstance(MultipleSelectionQuestionForm.class);
	private FormBeanFactory<NetworkBinaryQuestionForm> nbinqFormFactory = FormBeanFactory.getInstance(NetworkBinaryQuestionForm.class);
	
	private QuestionDAO questionDAO;
	private SurveyDAO surveyDAO;
	private BinaryqDAO binaryqDAO;
	private NumericqDAO numericqDAO;
	private LikertqDAO likertqDAO;
	private MultipleChoiceqDAO mcDAO;
	private ContinuousqDAO continuousqDAO;
	private EntityClassDAO ecDAO;
	private EntityDAO entityDAO;
	private UserDAO userDAO;
	private AnswerDAO answerDAO;
	
	public ViewSurveyAction(Model model) {
		questionDAO = model.getQuestionDAO();
		surveyDAO = model.getSurveyDAO();
		binaryqDAO = model.getBinaryqDAO();
		numericqDAO = model.getNumericqDAO();
		likertqDAO = model.getLikertqDAO();
		mcDAO = model.getMultipleChoiceqDAO();
		continuousqDAO = model.getContinuousqDAO();
		ecDAO = model.getEntityClassDAO();
		entityDAO = model.getEntityDAO();
		userDAO = model.getUserDAO();
		answerDAO = model.getAnswerDAO();
	}
    
	public String getName() {
		return "viewsurvey.do";
	}
    
    public String perform(HttpServletRequest request) {
    	
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        
        // Check if user is researcher or respondent
    	HttpSession session = request.getSession(false);
    	User user = (User) session.getAttribute("user");
    	
    	if (!(user.getType() == UserType.RESEARCHER || user.getType() == UserType.RESPONDENT)) {
    		errors.add("You are not a researcher or respondent!");
    		return "homepage.jsp";
    	}
    	
    	String button = request.getParameter("button");
    	
    	if (button == null){
    		String searchName = request.getParameter("searcher");
    		
    		if(searchName!=null){
				System.out.println("the seachName is " + searchName);
				int surveyNum;
				try {
					surveyNum = surveyDAO.size();
					if(surveyNum!=0){
						Survey[] usrSurvey = surveyDAO.getUserSurveys(user.getUserid());
						int surveyId = 1;
						for(Survey item : usrSurvey){
							if(searchName.equalsIgnoreCase(item.getTitle())){
								System.out.println("the suvey id is " + Integer.toString(surveyId));
								synchronized(session) {
				        			session.setAttribute("survey", surveyDAO.lookup(surveyId));
				        			
								}
			        			return "viewquestion.jsp";
							}
							surveyId++;
						}
					}else{
						request.setAttribute("message", "Sorry, we can not find survey.");
						return "researcher.jsp";
					}
				}catch (DAOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    		return "researcher.jsp";
    	}
		
		Survey survey = (Survey) session.getAttribute("survey");
		
		if (button.equals("View")) {
			try {
				String qidStr = request.getParameter("value");
		    	if (qidStr == null) {
		    		errors.add("Invalid question");
		    		if (user.getType() == UserType.RESEARCHER)
		    			return "researcher.jsp";
		    		else
		    			return "respondent.jsp";
		    	}
		    	int qid = Integer.parseInt(qidStr);
		    	Question question = questionDAO.lookup(qid);
		    	int maxQnum = questionDAO.getMaxQnumBySid(survey.getSid());
		    	
		    	synchronized(session) {
		    		session.setAttribute("question", question);
		    		session.setAttribute("maxqnum", maxQnum);	
		    	}
		    	
		    	QuestionTypeLookup(session, question, survey);
				
				return "viewquestion.jsp";
			} catch (DAOException e) {
				errors.add(e.getMessage());
				return "errors.jsp";
			}
		}
		
		if (button.equals("Previous Question") || button.equals("Next Question") || button.equals("Submit Answer and Return to List")) {
			try {
				// This button action must come from already viewing a question
				Question prevQuestion = (Question) session.getAttribute("question");
				if (prevQuestion == null) {
					errors.add("Invalid question");
					return "errors.jsp";
				}
				
				// Process the answers for the current question first if respondent
				if (user.getType() == UserType.RESPONDENT) {
					boolean[] completed = (boolean[]) session.getAttribute("completedlist");
					
					if (prevQuestion.getType() == QuestionType.BINARY) {
						BinaryQuestionForm form = binqFormFactory.create(request);
						
		            	// Validate for errors in the form
		        		errors.addAll(form.checkBinaryQuestionFormErrors());
		        		if (errors.size() != 0) {
		        			return "viewquestion.jsp";
		        		}
						
		        		// Delete the old answer and replace with new answer
		        		if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer oldAnswer = answerDAO.getAnswerByQidUsernameNN(prevQuestion.getQid(), user.getUserid());
		        			answerDAO.delete(oldAnswer.getQid(), oldAnswer.getUsername(), oldAnswer.getEntityname(), oldAnswer.getAnswer());
		        		}
		        		
		        		Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), "", form.getBinChoice());
		        		answerDAO.create(answer, questionDAO, userDAO, entityDAO);
					}
					if (prevQuestion.getType() == QuestionType.NUMERIC) {
						BasicAnswerForm form = basicFormFactory.create(request);
						
						errors.addAll(form.checkBasicAnswerFormErrors());
						try {
							int answer = Integer.parseInt(form.getAnswer());
							Numericq numericq = numericqDAO.lookup(prevQuestion.getQid());
							if (answer < numericq.getMin()) {
								errors.add("Answer must be greater or equals to " + numericq.getMin());
							}
							if (answer > numericq.getMax()) {
								errors.add("Answer must be less than or equals to " + numericq.getMax());
							}
						} catch (NumberFormatException e) {
							errors.add("Answer must be a number.");
						}
						if (errors.size() != 0) {
							return "viewquestion.jsp";
						}
						
						if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer oldAnswer = answerDAO.getAnswerByQidUsernameNN(prevQuestion.getQid(), user.getUserid());
		        			answerDAO.delete(oldAnswer.getQid(), oldAnswer.getUsername(), oldAnswer.getEntityname(), oldAnswer.getAnswer());
		        		}
						
		        		Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), "", form.getAnswer());
		        		answerDAO.create(answer, questionDAO, userDAO, entityDAO);
					}
					else if (prevQuestion.getType() == QuestionType.OPEN_ENDED) {
						BasicAnswerForm form = basicFormFactory.create(request);
						
		            	// Validate for errors in the form
		        		errors.addAll(form.checkBasicAnswerFormErrors());
		        		if (errors.size() != 0) {
		        			return "viewquestion.jsp";
		        		}
		        		
		        		if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer oldAnswer = answerDAO.getAnswerByQidUsernameNN(prevQuestion.getQid(), user.getUserid());
		        			answerDAO.delete(oldAnswer.getQid(), oldAnswer.getUsername(), oldAnswer.getEntityname(), oldAnswer.getAnswer());
		        		}
		        		
		        		Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), "", form.getAnswer());
		        		answerDAO.create(answer, questionDAO, userDAO, entityDAO);
					}
					else if (prevQuestion.getType() == QuestionType.LIKERT) {
						LikertQuestionForm form = likertFormFactory.create(request);
						
		            	// Validate for errors in the form
		        		errors.addAll(form.checkLikertQuestionFormErrors());
		        		if (errors.size() != 0) {
		        			return "viewquestion.jsp";
		        		}
		        		
		        		if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer oldAnswer = answerDAO.getAnswerByQidUsernameNN(prevQuestion.getQid(), user.getUserid());
		        			answerDAO.delete(oldAnswer.getQid(), oldAnswer.getUsername(), oldAnswer.getEntityname(), oldAnswer.getAnswer());
		        		}
		        		
		        		Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), "", form.getLikertChoice());
		        		answerDAO.create(answer, questionDAO, userDAO, entityDAO);
					}
					else if (prevQuestion.getType() == QuestionType.MULTIPLE_CHOICE) {
						MultipleChoiceQuestionForm form = mcFormFactory.create(request);
						
		            	// Validate for errors in the form
		        		errors.addAll(form.checkMultipleChoiceQuestionFormErrors());
		        		if (errors.size() != 0) {
		        			return "viewquestion.jsp";
		        		}
		        		
		        		if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer oldAnswer = answerDAO.getAnswerByQidUsernameNN(prevQuestion.getQid(), user.getUserid());
		        			answerDAO.delete(oldAnswer.getQid(), oldAnswer.getUsername(), oldAnswer.getEntityname(), oldAnswer.getAnswer());
		        		}
		        		
		        		Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), "", form.getChoice());
		        		answerDAO.create(answer, questionDAO, userDAO, entityDAO);
					}
					else if (prevQuestion.getType() == QuestionType.MULTIPLE_SELECTION) {
						MultipleSelectionQuestionForm form = msFormFactory.create(request);
						
		            	String answerStr = "";
		            	
		            	for (int i = 0; i < form.getChoice().length; i++) {
		            		answerStr += form.getChoice()[i] + " ";
		            	}
		        		
		            	if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer oldAnswer = answerDAO.getAnswerByQidUsernameNN(prevQuestion.getQid(), user.getUserid());
		        			answerDAO.delete(oldAnswer.getQid(), oldAnswer.getUsername(), oldAnswer.getEntityname(), oldAnswer.getAnswer());
		        		}
		            	
		        		Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), "", answerStr);
		        		answerDAO.create(answer, questionDAO, userDAO, entityDAO);
					}
					else if (prevQuestion.getType() == QuestionType.RANK_ORDER) {
						// Note: no formbean for this case, formbean not possible.
						MultipleChoiceq[] mcq = mcDAO.getChoicesByQid(prevQuestion.getQid());
						
						// Duplicate checking, whether it is between 1 - n (error checking)
						try {
							Set<Integer> set = new HashSet<Integer>();
							
							for (int i = 0; i < mcq.length; i++) {
								String answer = request.getParameter(mcq[i].getChoiceDesc());
								if (answer == null || answer.length() == 0)
									continue;
								
								int answerInt = Integer.parseInt(answer);
								/*if (answerInt < 1 || answerInt > mcq.getPos()) {
									errors.add("Number must be between 1 and " + mcq.getPos());
									return "viewquestion.jsp";
								}*/
								if (!set.add(answerInt)) {
									errors.add("Duplicate number detected, " + answerInt + " is duplicate");
									return "viewquestion.jsp";
								}
							}
							/*if (set.size() != mcq.getPos()) {
								errors.add("Please enter a number between 1 and " + mcq.getPos() + " for all your answers.");
								return "viewquestion.jsp";
							}*/
						} catch (NumberFormatException e) {
							errors.add("Please enter valid number for all your answers");
							return "viewquestion.jsp";
						}
						
						String answerStr = "";
						
						for (int i = 0; i < mcq.length; i++) {
							String ans = request.getParameter(mcq[i].getChoiceDesc());
							if (ans == null || ans.length() == 0)
								continue;
							else {
								answerStr += mcq[i].getChoiceDesc() + ":" + ans + " ";
							}
						}
						
						if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer oldAnswer = answerDAO.getAnswerByQidUsernameNN(prevQuestion.getQid(), user.getUserid());
		        			answerDAO.delete(oldAnswer.getQid(), oldAnswer.getUsername(), oldAnswer.getEntityname(), oldAnswer.getAnswer());
		        		}
						
						Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), "", answerStr);
						answerDAO.create(answer, questionDAO, userDAO, entityDAO);
					}
					else if (prevQuestion.getType() == QuestionType.CONTINUOUS) {
						BasicAnswerForm form = basicFormFactory.create(request);
						
		            	// Validate for errors in the form
		        		errors.addAll(form.checkBasicAnswerFormErrors());
		        		if (errors.size() != 0) {
		        			return "viewquestion.jsp";
		        		}
		        		
		        		if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer oldAnswer = answerDAO.getAnswerByQidUsernameNN(prevQuestion.getQid(), user.getUserid());
		        			answerDAO.delete(oldAnswer.getQid(), oldAnswer.getUsername(), oldAnswer.getEntityname(), oldAnswer.getAnswer());
		        		}
		        		
		        		Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), "", form.getAnswer());
		        		answerDAO.create(answer, questionDAO, userDAO, entityDAO);
					}
					else if (prevQuestion.getType() == QuestionType.NETWORK_BINARY) {
						NetworkBinaryQuestionForm form = nbinqFormFactory.create(request);
						
						if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer[] oldAnswer = answerDAO.getAnswerByQidUsername(prevQuestion.getQid(), user.getUserid());
		        			for (int i = 0; i < oldAnswer.length; i++)
		        				answerDAO.delete(oldAnswer[i].getQid(), oldAnswer[i].getUsername(), oldAnswer[i].getEntityname(), oldAnswer[i].getAnswer());
		        		}
						
		        		if (form.getNbinChoice() == null || form.getNbinChoice().length == 0) { // Nothing was chosen
		        			Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), "", "-1");
		        			answerDAO.create(answer, questionDAO, userDAO, entityDAO);
		        		}
		        		else { // At least one checkbox was chosen
		        			for (int i = 0; i < form.getNbinChoice().length; i++) {
		        				Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), form.getNbinChoice()[i], "1");
		        				answerDAO.create(answer, questionDAO, userDAO, entityDAO);
		        			}
		        		}
					}
					else if (prevQuestion.getType() == QuestionType.NETWORK_OPEN) {
						BasicAnswerForm form = basicFormFactory.create(request);
						
		            	// Validate for errors in the form
		        		errors.addAll(form.checkBasicAnswerFormErrors());
		        		if (errors.size() != 0) {
		        			return "viewquestion.jsp";
		        		}
		        		
		        		if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer[] oldAnswer = answerDAO.getAnswerByQidUsername(prevQuestion.getQid(), user.getUserid());
		        			for (int i = 0; i < oldAnswer.length; i++)
		        				answerDAO.delete(oldAnswer[i].getQid(), oldAnswer[i].getUsername(), oldAnswer[i].getEntityname(), oldAnswer[i].getAnswer());
		        		}

		        		// Parse whenever there is a comma, trailing whitespace removed
		        		String[] answers = form.getAnswer().split(", *+");
		        		EntityClass ec = ecDAO.lookupBySidName(survey.getSid(), prevQuestion.getEntityTo());
		        		Entity[] elist = entityDAO.getEntityByEcid(ec.getEcid());
		        		for (int i = 0; i < answers.length; i++) {
		        			boolean match = false;
		        			for (int j = 0; j < elist.length; j++) {
		        				if (answers[i].equals(elist[j].getName())) {
		        					match = true;
		        					break;
		        				}
		        			}
		        			if (!match) {
		        				errors.add("Some of the answers provided did not match the provided entities.");
		        				return "viewquestion.jsp";
		        			}
		        		}
		        		
		        		// If code reached here, this means all entries in answer matched
		        		for (int i = 0; i < answers.length; i++) {
		        			Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), answers[i], "1");
		        			answerDAO.create(answer, questionDAO, userDAO, entityDAO);
		        		}
					}
					else if (prevQuestion.getType() == QuestionType.NETWORK_WEIGHTED) {
						// Note: no formbean for this case, formbean not possible.
						EntityClass ec = ecDAO.lookupBySidName(survey.getSid(), prevQuestion.getEntityTo());
		        		Entity[] elist = entityDAO.getEntityByEcid(ec.getEcid());
						
						// Error checking for empty answers
						for (int i = 0; i < elist.length; i++) {
							String answer = request.getParameter(elist[i].getName());
							if (answer == null) {
								errors.add("Please choose an answer for all entities.");
								return "viewquestion.jsp";
							}
						}
						
						if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer[] oldAnswer = answerDAO.getAnswerByQidUsername(prevQuestion.getQid(), user.getUserid());
		        			for (int i = 0; i < oldAnswer.length; i++)
		        				answerDAO.delete(oldAnswer[i].getQid(), oldAnswer[i].getUsername(), oldAnswer[i].getEntityname(), oldAnswer[i].getAnswer());
		        		}
						
						// no errors, can safely add to the database
						for (int i = 0; i < elist.length; i++) {
							String ans = request.getParameter(elist[i].getName());
							Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), elist[i].getName(), ans);
							answerDAO.create(answer, questionDAO, userDAO, entityDAO);
						}
					}
					else if (prevQuestion.getType() == QuestionType.NETWORK_WEIGHTED_CONTINUOUS) {
						// Note: no formbean for this case, formbean not possible.
						EntityClass ec = ecDAO.lookupBySidName(survey.getSid(), prevQuestion.getEntityTo());
		        		Entity[] elist = entityDAO.getEntityByEcid(ec.getEcid());
						
						// Error checking for empty answers
						for (int i = 0; i < elist.length; i++) {
							String answer = request.getParameter(elist[i].getName());
							if (answer == null) {
								errors.add("Please choose an answer for all entities.");
								return "viewquestion.jsp";
							}
						}
						
						if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer[] oldAnswer = answerDAO.getAnswerByQidUsername(prevQuestion.getQid(), user.getUserid());
		        			for (int i = 0; i < oldAnswer.length; i++)
		        				answerDAO.delete(oldAnswer[i].getQid(), oldAnswer[i].getUsername(), oldAnswer[i].getEntityname(), oldAnswer[i].getAnswer());
		        		}
						
						// no errors, can safely add to the database
						for (int i = 0; i < elist.length; i++) {
							String ans = request.getParameter(elist[i].getName());
							Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), elist[i].getName(), ans);
							answerDAO.create(answer, questionDAO, userDAO, entityDAO);
						}
					}
					else if (prevQuestion.getType() == QuestionType.NETWORK_RANK_ORDER) {
						// Note: no formbean for this case, formbean not possible.
						EntityClass ec = ecDAO.lookupBySidName(survey.getSid(), prevQuestion.getEntityTo());
		        		Entity[] elist = entityDAO.getEntityByEcid(ec.getEcid());
						MultipleChoiceq mcq = mcDAO.getChoicesByQidRO(prevQuestion.getQid());
						
						// Duplicate checking, whether it is between 1 - n (error checking)
						try {
							Set<Integer> set = new HashSet<Integer>();
							
							for (int i = 0; i < elist.length; i++) {
								String answerStr = request.getParameter(elist[i].getName());
								if (answerStr == null || answerStr.length() == 0)
									continue;
								
								int answer = Integer.parseInt(answerStr);
								if (answer < 1 || answer > mcq.getPos()) {
									errors.add("Number must be between 1 and " + mcq.getPos());
									return "viewquestion.jsp";
								}
								if (!set.add(answer)) {
									errors.add("Duplicate number detected, " + answer + " is duplicate");
									return "viewquestion.jsp";
								}
							}
							if (set.size() != mcq.getPos()) {
								errors.add("Please enter a number between 1 and " + mcq.getPos() + " for all your answers.");
								return "viewquestion.jsp";
							}
						} catch (NumberFormatException e) {
							errors.add("Please enter valid number for all your answers");
							return "viewquestion.jsp";
						}
						
						if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer[] oldAnswer = answerDAO.getAnswerByQidUsername(prevQuestion.getQid(), user.getUserid());
		        			for (int i = 0; i < oldAnswer.length; i++)
		        				answerDAO.delete(oldAnswer[i].getQid(), oldAnswer[i].getUsername(), oldAnswer[i].getEntityname(), oldAnswer[i].getAnswer());
		        		}
						
						for (int i = 0; i < elist.length; i++) {
							String ans = request.getParameter(elist[i].getName());
							if (ans == null || ans.length() == 0)
								continue;
							else {
								int ansInt = mcq.getPos() - Integer.parseInt(ans) + 1;
								Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), elist[i].getName(), new Integer(ansInt).toString());
								answerDAO.create(answer, questionDAO, userDAO, entityDAO);
							}
						}
					}
					else if (prevQuestion.getType() == QuestionType.NETWORK_SOCIO_COGNITIVE) {
						
						if (completed[prevQuestion.getQnum() - 1]) {
		        			Answer[] oldAnswer = answerDAO.getAnswerByQidUsername(prevQuestion.getQid(), user.getUserid());
		        			for (int i = 0; i < oldAnswer.length; i++)
		        				answerDAO.delete(oldAnswer[i].getQid(), oldAnswer[i].getUsername(), oldAnswer[i].getEntityname(), oldAnswer[i].getAnswer());
		        		}
						
						// Note: no formbean for this case, formbean not possible.
						EntityClass ecsource = ecDAO.lookupBySidName(survey.getSid(), prevQuestion.getEntityFrom());
						Entity[] elistsource = entityDAO.getEntityByEcid(ecsource.getEcid());
						
						for (int i = 0; i < elistsource.length; i++) {
							String[] answers = request.getParameterValues(elistsource[i].getName());
							if (answers == null || answers.length == 0)
								continue;
							
							for (int j = 0; j < answers.length; j++) {
								Answer answer = new Answer(prevQuestion.getQid(), user.getUserid(), elistsource[i].getName(), answers[j]);
								answerDAO.create(answer, questionDAO, userDAO, entityDAO);
							}
						}
					}
					
					// Mark the question as completed
					completed[prevQuestion.getQnum() - 1] = true;
					synchronized(session) {
						session.setAttribute("completedlist", completed);
					}
				}
				
				if (button.equals("Submit Answer and Return to List")) {
					synchronized(session) {
						session.removeAttribute("question");
					}
					return "surveysummary.jsp";
				}
				else {
					int newQnum; 
					if (button.equals("Previous Question"))
						newQnum = prevQuestion.getQnum() - 1;
					else
						newQnum = prevQuestion.getQnum() + 1;
					
					Question question = questionDAO.getQuestionBySidQnum(survey.getSid(), newQnum);
					QuestionTypeLookup(session, question, survey);
					synchronized(session) {
						session.setAttribute("question", question);
					}
					return "viewquestion.jsp";
				}
			} catch (DAOException e) {
				errors.add(e.getMessage());
				return "errors.jsp";
			} catch (FormBeanException e) {
				errors.add(e.getMessage());
				return "errors.jsp";
			}
		}
		
		if (button.equals("Go Back to List of Questions")) {
			synchronized(session) {
				session.removeAttribute("question");
			}
			return "surveysummary.jsp";
		}
		
		errors.add("Illegal button value of " + button);
		return "errors.jsp";
    }
    
    private void QuestionTypeLookup(HttpSession session, Question question, Survey survey) throws DAOException {
    	if (question.getType() == QuestionType.BINARY) {
			session.setAttribute("binaryq", binaryqDAO.lookup(question.getQid()));
		}
		else if (question.getType() == QuestionType.NUMERIC) {
			session.setAttribute("numericq", numericqDAO.lookup(question.getQid()));
		}
		else if (question.getType() == QuestionType.OPEN_ENDED) {}
		else if (question.getType() == QuestionType.LIKERT) {
			session.setAttribute("likertq", likertqDAO.lookup(question.getQid()));
		}
		else if (question.getType() == QuestionType.MULTIPLE_CHOICE) {
			session.setAttribute("multiplechoiceq", mcDAO.getChoicesByQid(question.getQid()));
		}
		else if (question.getType() == QuestionType.MULTIPLE_SELECTION) {
			session.setAttribute("multiplechoiceq", mcDAO.getChoicesByQid(question.getQid()));
		}
		else if (question.getType() == QuestionType.RANK_ORDER) {
			session.setAttribute("multiplechoiceq", mcDAO.getChoicesByQid(question.getQid()));
		}
		else if (question.getType() == QuestionType.CONTINUOUS) {
			session.setAttribute("continuousq", continuousqDAO.lookup(question.getQid()));
		}
		else if (question.getType() == QuestionType.NETWORK_BINARY) {
			EntityClass ec = ecDAO.lookupBySidName(survey.getSid(), question.getEntityTo());
			session.setAttribute("entitylist", entityDAO.getEntityByEcid(ec.getEcid()));
		}
		else if (question.getType() == QuestionType.NETWORK_OPEN) {}
		else if (question.getType() == QuestionType.NETWORK_WEIGHTED) {
			EntityClass ec = ecDAO.lookupBySidName(survey.getSid(), question.getEntityTo());
			session.setAttribute("entitylist", entityDAO.getEntityByEcid(ec.getEcid()));
			session.setAttribute("multiplechoiceq", mcDAO.getChoicesByQid(question.getQid()));
		}
		else if (question.getType() == QuestionType.NETWORK_WEIGHTED_CONTINUOUS) {
			EntityClass ec = ecDAO.lookupBySidName(survey.getSid(), question.getEntityTo());
			session.setAttribute("entitylist", entityDAO.getEntityByEcid(ec.getEcid()));
			session.setAttribute("continuousq", continuousqDAO.lookup(question.getQid()));
		}
		else if (question.getType() == QuestionType.NETWORK_RANK_ORDER) {
			EntityClass ec = ecDAO.lookupBySidName(survey.getSid(), question.getEntityTo());
			session.setAttribute("entitylist", entityDAO.getEntityByEcid(ec.getEcid()));
			session.setAttribute("rankorderq", mcDAO.getChoicesByQidRO(question.getQid()));
		}
		else if (question.getType() == QuestionType.NETWORK_SOCIO_COGNITIVE) {
			EntityClass ecsource = ecDAO.lookupBySidName(survey.getSid(), question.getEntityFrom());
			EntityClass ectarget = ecDAO.lookupBySidName(survey.getSid(), question.getEntityTo());
			session.setAttribute("entitylistsource", entityDAO.getEntityByEcid(ecsource.getEcid()));
			session.setAttribute("entitylisttarget", entityDAO.getEntityByEcid(ectarget.getEcid()));
		}
    }

}
